import React, { useRef, useState } from 'react';
import { ProTable, ActionType, ProColumns } from '@ant-design/pro-components';
import { Button, message, Popconfirm, Tag } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import tenantService from '../../services/tenants';
import { Tenant } from '../../types';

const TenantList: React.FC = () => {
  const actionRef = useRef<ActionType>(null);
  const navigate = useNavigate();
  const [loading, setLoading] = useState(false);

  const fetchTenants = async (params: any) => {
    try {
      const response = await tenantService.getTenants({
        skip: (params.current - 1) * params.pageSize,
        limit: params.pageSize,
      });
      return {
        data: response.items,
        success: true,
        total: response.total,
      };
    } catch (error: any) {
      message.error('Failed to fetch tenants');
      return {
        data: [],
        success: false,
        total: 0,
      };
    }
  };

  const handleDelete = async (id: number) => {
    setLoading(true);
    try {
      await tenantService.deleteTenant(id);
      message.success('Tenant deleted successfully');
      actionRef.current?.reload();
    } catch (error: any) {
      message.error(error.response?.data?.detail || 'Failed to delete tenant');
    } finally {
      setLoading(false);
    }
  };

  const columns: ProColumns<Tenant>[] = [
    {
      title: 'ID',
      dataIndex: 'id',
      width: 80,
      search: false,
    },
    {
      title: 'Name',
      dataIndex: 'name',
      copyable: true,
    },
    {
      title: 'Tenant Key',
      dataIndex: 'tenantKey',
      copyable: true,
    },
    {
      title: 'Description',
      dataIndex: 'description',
      search: false,
      ellipsis: true,
    },
    {
      title: 'Status',
      dataIndex: 'isActive',
      search: false,
      render: (_, record) => (
        <Tag color={record.isActive ? 'green' : 'red'}>
          {record.isActive ? 'Active' : 'Inactive'}
        </Tag>
      ),
    },
    {
      title: 'Created At',
      dataIndex: 'createdAt',
      valueType: 'dateTime',
      search: false,
    },
    {
      title: 'Action',
      valueType: 'option',
      width: 200,
      render: (_, record) => [
        <Button
          key="edit"
          type="link"
          icon={<EditOutlined />}
          onClick={() => navigate(`/tenants/${record.id}/edit`)}
        >
          Edit
        </Button>,
        <Popconfirm
          key="delete"
          title="Are you sure to delete this tenant?"
          onConfirm={() => handleDelete(record.id)}
          okText="Yes"
          cancelText="No"
        >
          <Button type="link" danger icon={<DeleteOutlined />} loading={loading}>
            Delete
          </Button>
        </Popconfirm>,
      ],
    },
  ];

  return (
    <ProTable<Tenant>
      columns={columns}
      actionRef={actionRef}
      request={fetchTenants}
      rowKey="id"
      search={{
        labelWidth: 'auto',
      }}
      pagination={{
        defaultPageSize: 10,
        showSizeChanger: true,
      }}
      dateFormatter="string"
      headerTitle="Tenant Management"
      toolBarRender={() => [
        <Button
          key="button"
          icon={<PlusOutlined />}
          onClick={() => navigate('/tenants/new')}
          type="primary"
        >
          Create Tenant
        </Button>,
      ]}
    />
  );
};

export default TenantList;
